package com.manage.competition.service.impl;

import com.manage.competition.entity.*;
import com.manage.competition.mapper.CompetitionMapper;
import com.manage.competition.repository.CompetitionRepository;
import com.manage.competition.service.*;
import com.manage.competition.util.CurrentUserUtil;
import com.manage.competition.util.SnowflakeUtil;
import com.manage.competition.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create with IDEA
 *
 * @Author: gitee.com/KamisamaXX
 * @Date: Create in 19:44 2019/3/24
 * @Description:
 */
@Service
@Slf4j
public class CompetitionServiceImpl extends BaseServiceImpl implements ICompetitionService {

    static final private int PUBLISH = 3;
    static final private int UNPUBLISH = 0;


    @Autowired
    private CompetitionRepository competitionRepository;

    @Autowired
    private CompetitionMapper competitionMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private IAdvertisePictureService advertisePictureService;

    @Autowired
    private ISignupInformationService signupInformationService;

    @Autowired
    private IFillInItemService fillInItemService;

    @Autowired
    private ISingleOptionService singleOptionService;

    @Autowired
    private IDoubleOptionService doubleOptionService;

    @Autowired
    private ICompetitionInformationService competitionInformationService;

    @Autowired
    private IContactService contactService;

    @Autowired
    private IOrganizerService organizerService;

    @Autowired
    private IExaminationPaperService examinationPaperService;

    @Autowired
    private IExaminationColumnService examinationColumnService;

    @Autowired
    private IExaminationQuestionService examinationQuestionService;

    @Autowired
    private IEnrollCollectionService enrollCollectionService;

    @Autowired
    private IAnswerPaperService answerPaperService;

    @Autowired
    private ICompetitionReviewService competitionReviewService;

    @Autowired
    private ICompetitionScoreService competitionScoreService;


    private HashMap<Long, Long> competitionEdit = new HashMap<>();

    @Override
    public List<CompetitionVo> findCompetitionListByStatus(int status) {
        List<CompetitionVo> competitionVoList = new ArrayList<>();
        List<Competition> competitionList = competitionRepository.findByStatus(status);
        for (Competition competition :
                competitionList) {
            CompetitionVo competitionVo = new CompetitionVo();
            BeanUtils.copyProperties(competition, competitionVo);
            competitionVoList.add(competitionVo);
            if (competition.getAdvertisePictureId() != null && competition.getInformationId() != null) {
                AdvertisePicture advertisePicture = advertisePictureService.findById(competition.getAdvertisePictureId());
                CompetitionInformation competitionInformation = competitionInformationService.getById(competition.getInformationId());

                AdvertisePictureVo advertisePictureVo = new AdvertisePictureVo();
                CompetitionInformationVo competitionInformationVo = new CompetitionInformationVo();

                BeanUtils.copyProperties(advertisePicture, advertisePictureVo);
                BeanUtils.copyProperties(competitionInformation, competitionInformationVo);

                String big = "http://localhost:8080/image/" + advertisePictureVo.getAdvertisePictureBig();
                String samll = "http://localhost:8080/image/" + advertisePictureVo.getAdvertisePictureSmall();

                advertisePictureVo.setAdvertisePictureBig(big);
                advertisePictureVo.setAdvertisePictureSmall(samll);

                competitionVo.setAdvertisePictureVo(advertisePictureVo);
                competitionVo.setCompetitionInformationVo(competitionInformationVo);
            }

        }
        return competitionVoList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public long newCompetition() {
        User currentUser = CurrentUserUtil.getCurrentUser();
        long id = SnowflakeUtil.nextId();
        long advertiseId = SnowflakeUtil.nextId();
        long signupInfoId = SnowflakeUtil.nextId();
        long informationId = SnowflakeUtil.nextId();
        long organizerId = SnowflakeUtil.nextId();
        long contactId = SnowflakeUtil.nextId();
        long examId = SnowflakeUtil.nextId();
        Competition competition = new Competition();

        // 新建宣传图
        AdvertisePicture advertisePicture = new AdvertisePicture();
        advertisePicture.setId(advertiseId);
        advertisePictureService.insert(advertisePicture);

        // 新建报名信息节点
        SignUpInformation signUpInformation = new SignUpInformation();
        signUpInformation.setId(signupInfoId);
        signupInformationService.insert(signUpInformation);

        // 竞赛基本信息
        CompetitionInformation competitionInformation = new CompetitionInformation();
        competitionInformation.setId(informationId);
        competitionInformationService.insert(competitionInformation);

        // 活动单位
        Organizer organizer = new Organizer();
        organizer.setId(organizerId);
        organizerService.insert(organizer);

        // 联系信息
        Contact contact = new Contact();
        contact.setId(contactId);
        contactService.insert(contact);

        // 新建试卷
        ExaminationPaper examinationPaper = new ExaminationPaper();
        examinationPaper.setId(examId);
        examinationPaperService.insert(examinationPaper);

        // 新建竞赛
        competition.setId(id);
        competition.setAdvertisePictureId(advertiseId);
        competition.setSignupInformationId(signupInfoId);
        competition.setInformationId(informationId);
        competition.setContactId(contactId);
        competition.setOrganizerId(organizerId);
        competition.setExamPaperId(examId);
        competition.setCreateUser(currentUser.getUsername());
        competition.setUpdateUser(currentUser.getUsername());
        competitionMapper.insert(competition);
        return id;
    }

    @Override
    public int publishCompetition(long competitionId) {
        return competitionMapper.updateStatus(competitionId, PUBLISH);
    }

    @Override
    public int setFillItem(String title, boolean type) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        FillInItem fillInItem = new FillInItem();
        fillInItem.setSignupInformationId(competition.getSignupInformationId());
        fillInItem.setTitle(title);
        fillInItem.setType(type);
        return fillInItemService.insert(fillInItem);
    }

    @Override
    public int setSingleOption(String title, String options, boolean type) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        SingleLevelOption singleLevelOption = new SingleLevelOption();
        singleLevelOption.setSignupInformationId(competition.getSignupInformationId());
        singleLevelOption.setTitle(title);
        singleLevelOption.setOption(options);
        singleLevelOption.setType(type);
        return singleOptionService.insert(singleLevelOption);
    }

    @Override
    public int setDoubleOption(String title, String firstOptions, String secondOptions, boolean type) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        DoubleLevelOption doubleLevelOption = new DoubleLevelOption();
        doubleLevelOption.setSignupInformationId(competition.getSignupInformationId());
        doubleLevelOption.setTitle(title);
        doubleLevelOption.setFirstOption(firstOptions);
        doubleLevelOption.setSecondOption(secondOptions);
        doubleLevelOption.setType(type);
        return doubleOptionService.insert(doubleLevelOption);
    }

    @Override
    public SignUpInfoVo getSignUpInfo() {
        long currentCompetition = getCurrentCompetition();
        Competition competition = competitionRepository.findById(currentCompetition).orElse(null);
        long singupInfoId = competition.getSignupInformationId();
        List<FillInItemVo> fillInItems = fillInItemService.findBySignupInfo(singupInfoId);
        List<SingleLevelOptionVo> singleLevelOptions = singleOptionService.findBySignupInfo(singupInfoId);
        List<DoubleLevelOptionVo> doubleLevelOptions = doubleOptionService.findBySignupInfo(singupInfoId);

        SignUpInfoVo signUpInfoVo = new SignUpInfoVo();
        signUpInfoVo.setId(singupInfoId);
        signUpInfoVo.setFillInItem(fillInItems);
        signUpInfoVo.setSingleLevelOption(singleLevelOptions);
        signUpInfoVo.setDoubleLevelOption(doubleLevelOptions);

        return signUpInfoVo;
    }

    @Override
    public int deleteOption(long id) {
        if (fillInItemService.deleteOption(id) > 0) {
            return 1;
        } else if (singleOptionService.deleteOption(id) > 0) {
            return 1;
        } else if (doubleOptionService.deleteOption(id) > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public String getAdvertisePicture(String type) {
        long currentCompetition = getCurrentCompetition();
        Competition competition = competitionRepository.findById(currentCompetition).orElse(null);
        AdvertisePicture advertisePicture = advertisePictureService.findById(competition.getAdvertisePictureId());
        if ("big".equals(type)) {
            return advertisePicture.getAdvertisePictureBig();
        } else if ("small".equals(type)) {
            return advertisePicture.getAdvertisePictureSmall();
        }
        return null;
    }


    @Override
    public int deleteAdvertisePicture(String type) {
        long currentCompetition = getCurrentCompetition();
        Competition competition = competitionRepository.findById(currentCompetition).orElse(null);
        AdvertisePicture advertisePicture = advertisePictureService.findById(competition.getAdvertisePictureId());
        if ("big".equals(type)) {
            try {
                fileService.delete(advertisePicture.getAdvertisePictureBig());
            }catch (NullPointerException e){
                e.printStackTrace();
                return 0;
            }
            advertisePicture.setAdvertisePictureBig(null);
            return advertisePictureService.updateByPrimaryKey(advertisePicture);
        } else if ("small".equals(type)) {
            if (fileService.delete(advertisePicture.getAdvertisePictureSmall())) {
                advertisePicture.setAdvertisePictureSmall("");
                return advertisePictureService.updateByPrimaryKey(advertisePicture);
            }
        }
        return 0;
    }

    @Override
    public String upload(MultipartFile file, String type) {
        String targetFileName = fileService.upload(file);
        if (!targetFileName.isEmpty()) {
            AdvertisePicture advertisePicture = new AdvertisePicture();
            if ("big".equals(type)) {
                advertisePicture.setAdvertisePictureBig(targetFileName);
            } else if ("small".equals(type)) {
                advertisePicture.setAdvertisePictureSmall(targetFileName);
            }
            // 取到id
            long advertisePictureId = 0;
            long currentCompetition = getCurrentCompetition();

            Competition competition = competitionRepository.findById(currentCompetition).orElse(null);

            // 更新
            advertisePictureId = competition.getAdvertisePictureId();
            advertisePicture.setId(advertisePictureId);
            advertisePictureService.updateByPrimaryKey(advertisePicture);

            return targetFileName;
        }
        return null;
    }

    @Override
    public int setCompetitionInformation(CompetitionInformation competitionInformation) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long informationId = competition.getInformationId();
        competitionInformation.setId(informationId);
        return competitionInformationService.update(competitionInformation);
    }

    @Override
    public CompetitionInformationVo getCompetitionInformation() {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long informationId = competition.getInformationId();
        CompetitionInformation information = competitionInformationService.getById(informationId);
        CompetitionInformationVo informationVo = new CompetitionInformationVo();
        BeanUtils.copyProperties(information, informationVo);
        return informationVo;
    }

    @Override
    public int enrollCompetition(long competitionId) {
        User user = CurrentUserUtil.getCurrentUser();
        Competition competition = competitionRepository.findById(competitionId).orElse(null);
        EnrollCollection enrollCollectionOld = enrollCollectionService.findByUserIdAndCompetitionId(user.getId(), competitionId);
        if (competition != null && enrollCollectionOld == null) {
            long id = SnowflakeUtil.nextId();
            EnrollCollection enrollCollection = new EnrollCollection();
            enrollCollection.setUserId(user.getId());
            enrollCollection.setId(id);
            enrollCollection.setCompetitionId(competitionId);
            enrollCollection.setStatus(1);
            return enrollCollectionService.insert(enrollCollection);
        }
        return 0;
    }

    @Override
    public int enrollCompetitionMessage(EnrollMessageVo vo) {
        return 0;
    }

    @Override
    public int setContact(Contact contact) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long contactId = competition.getContactId();
        contact.setId(contactId);
        return contactService.update(contact);
    }

    @Override
    public ContactVo getContact() {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long contactId = competition.getContactId();
        Contact contact = contactService.getById(contactId);
        ContactVo contactVo = new ContactVo();
        BeanUtils.copyProperties(contact, contactVo);
        return contactVo;
    }

    @Override
    public int setOrganizer(Organizer organizer) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long organizerId = competition.getOrganizerId();
        organizer.setId(organizerId);
        return organizerService.update(organizer);
    }

    @Override
    public CompetitionVo getCurrentCompetitionDetail() {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            CompetitionVo competitionVo = new CompetitionVo();
            BeanUtils.copyProperties(competition, competitionVo);

            CompetitionInformation competitionInformation = competitionInformationService.getById(competition.getInformationId());
            CompetitionInformationVo competitionInformationVo = new CompetitionInformationVo();
            BeanUtils.copyProperties(competitionInformation, competitionInformationVo);

            competitionVo.setCompetitionInformationVo(competitionInformationVo);

            return competitionVo;
        }
        return null;
    }

    @Override
    public CompetitionDetailVo getCompetitionDetail(long competitionId) {
        Competition competition = competitionRepository.findById(competitionId).orElse(null);
        CompetitionDetailVo competitionDetailVo = new CompetitionDetailVo();
        if (competition != null) {
            CompetitionVo competitionVo = new CompetitionVo();
            BeanUtils.copyProperties(competition, competitionVo);

            CompetitionInformation competitionInformation = competitionInformationService.getById(competition.getInformationId());
            CompetitionInformationVo competitionInformationVo = new CompetitionInformationVo();
            BeanUtils.copyProperties(competitionInformation, competitionInformationVo);

            AdvertisePicture advertisePicture = advertisePictureService.findById(competition.getAdvertisePictureId());
            AdvertisePictureVo advertisePictureVo = new AdvertisePictureVo();
            BeanUtils.copyProperties(advertisePicture, advertisePictureVo);

            Contact contact = contactService.getById(competition.getContactId());
            ContactVo contactVo = new ContactVo();
            BeanUtils.copyProperties(contact, contactVo);

            Organizer organizer = organizerService.getById(competition.getOrganizerId());
            OrganizerVo organizerVo = new OrganizerVo();
            BeanUtils.copyProperties(organizer, organizerVo);

            ExaminationPaper paper = examinationPaperService.findById(competition.getExamPaperId());
            ExaminationPaperVo paperVo = new ExaminationPaperVo();
            BeanUtils.copyProperties(paper, paperVo);


            competitionDetailVo.setCompetitionVo(competitionVo);
            competitionDetailVo.setCompetitionInformationVo(competitionInformationVo);
            competitionDetailVo.setAdvertisePictureVo(advertisePictureVo);
            competitionDetailVo.setContactVo(contactVo);
            competitionDetailVo.setOrganizerVo(organizerVo);
            competitionDetailVo.setFillInItemVo(fillInItemService.findBySignupInfo(competition.getSignupInformationId()));
            competitionDetailVo.setSingleLevelOptionVo(singleOptionService.findBySignupInfo(competition.getSignupInformationId()));
            competitionDetailVo.setDoubleLevelOptionVo(doubleOptionService.findBySignupInfo(competition.getSignupInformationId()));
            competitionDetailVo.setPaperVo(paperVo);

        }
        return competitionDetailVo;
    }

    @Override
    public ExaminationPaperVo getExaminationPaper() {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            long examId = competition.getExamPaperId();
            ExaminationPaper examinationPaper = examinationPaperService.findById(examId);
            ExaminationPaperVo examinationPaperVo = new ExaminationPaperVo();
            BeanUtils.copyProperties(examinationPaper, examinationPaperVo);
            return examinationPaperVo;
        }

        return null;
    }

    @Override
    public UserPaperVo getUserExaminationPaper(long competitionId, Long userId) {
        Competition competition = competitionRepository.findById(competitionId).orElse(null);
        if (competition != null) {
            UserPaperVo paperVo = new UserPaperVo();

            ExaminationPaper examinationPaper = examinationPaperService.findById(competition.getExamPaperId());
            ExaminationPaperVo examinationPaperVo = new ExaminationPaperVo();
            BeanUtils.copyProperties(examinationPaper, examinationPaperVo);

            List<ExaminationColumnVo> columnVos = examinationColumnService.findByExamId(competition.getExamPaperId());
            List<UserColumnVo> userColumnVos = new ArrayList<>();
            for (ExaminationColumnVo vo : columnVos) {
                UserColumnVo userColumnVo = new UserColumnVo();
                BeanUtils.copyProperties(vo, userColumnVo);
                List<ExaminationQuestionVo> questionVos = examinationQuestionService.findByColumnId(vo.getId());
                List<AnswerPaperVo> answerPaperVos = new ArrayList<>();
                for (ExaminationQuestionVo questionVo : questionVos) {
                    AnswerPaper paper = new AnswerPaper();
                    if (userId == null) {
                        paper = answerPaperService.findByQuestionIdAndUserId(CurrentUserUtil.getCurrentUser().getId(), questionVo.getId());
                    } else {
                        paper = answerPaperService.findByQuestionIdAndUserId(userId, questionVo.getId());
                    }
                    AnswerPaperVo answerPaperVo = new AnswerPaperVo();
                    if (paper != null) {
                        BeanUtils.copyProperties(paper, answerPaperVo);
                    }
                    answerPaperVos.add(answerPaperVo);
                }
                userColumnVo.setAnswerPaperVos(answerPaperVos);
                userColumnVo.setQuestionVos(questionVos);
                userColumnVos.add(userColumnVo);
            }

            paperVo.setPaperVo(examinationPaperVo);
            paperVo.setColumnsVo(userColumnVos);

            return paperVo;
        }
        return null;
    }

    @Override
    public int setExamPaper(ExaminationPaper paper) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            if (paper.getId().equals(competition.getExamPaperId())) {
                return examinationPaperService.update(paper);
            }
        }
        return 0;
    }

    @Override
    public List<ExaminationColumnVo> getExaminationColumn(long paperId) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null && competition.getExamPaperId() == paperId) {
            long examId = competition.getExamPaperId();
            List<ExaminationColumnVo> list = examinationColumnService.findByExamId(examId);
            return list;
        }
        return null;
    }

    @Override
    public Long createExamColumn(long paperId) {
        ExaminationColumn column = new ExaminationColumn();
        column.setTitle("新建栏目");
        column.setPaperId(paperId);
        Long id = SnowflakeUtil.nextId();
        column.setId(id);
        if(examinationColumnService.insert(column)>0){
            return id;
        }
        return null;
    }

    @Override
    public int setExamColumn(ExaminationColumn column) {
        return examinationColumnService.update(column);
    }

    @Override
    public int createExamQuestion(long columnId) {
        ExaminationQuestions examinationQuestions = new ExaminationQuestions();
        examinationQuestions.setColumnId(columnId);
        examinationQuestions.setType(5);
        examinationQuestions.setAnswer("（/*请上传作品*/）");
        return examinationQuestionService.insert(examinationQuestions);
    }

    @Override
    public int setExamQuestion(ExaminationQuestions questions) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            long examId = competition.getExamPaperId();
            if (examinationColumnService.findByIdAndPaperId(questions.getColumnId(), examId) != null) {

                if (questions.getType() == 5 && questions.getAnswer().isEmpty()) {
                    questions.setAnswer("（/*本题是开放式回答*/）");
                }
                return examinationQuestionService.update(questions);
            }
        }
        return 0;
    }

    @Override
    public List<ExaminationQuestionVo> getExaminationQuestion(long columnId) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            long examId = competition.getExamPaperId();
            if (examId == examinationColumnService.findById(columnId).getPaperId()) {
                return examinationQuestionService.findByColumnId(columnId);
            }
        }
        return null;
    }

    @Override
    public Map<String, List<ExaminationQuestionVo>> getExaminationQuestionByColumn(List<ExaminationColumn> columnIds) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        Map<String, List<ExaminationQuestionVo>> listMap = new HashMap<>();
        if (competition != null) {
            long examId = competition.getExamPaperId();
            for (ExaminationColumn columnId : columnIds) {
                if (examId == examinationColumnService.findById(columnId.getId()).getPaperId()) {
                    listMap.put(columnId.getId().toString(), examinationQuestionService.findByColumnId(columnId.getId()));
                }
            }
        }
        return listMap;
    }

    @Override
    public int deleteExamQuestion(ExaminationQuestions questions) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            long examId = competition.getExamPaperId();
            if (examId == examinationColumnService.findById(questions.getColumnId()).getPaperId()) {
                return examinationQuestionService.delete(questions);
            }
        }
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteExamColumn(ExaminationColumn column) {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        if (competition != null) {
            long examId = competition.getExamPaperId();
            if (column.getPaperId().equals(examId)) {
                List<ExaminationQuestionVo> examinationQuestionVos = examinationQuestionService.findByColumnId(column.getId());
                for (ExaminationQuestionVo vo : examinationQuestionVos) {
                    ExaminationQuestions questions = new ExaminationQuestions();
                    BeanUtils.copyProperties(vo, questions);
                    examinationQuestionService.delete(questions);
                }

                return examinationColumnService.delete(column);
            }
        }
        return 0;
    }

    @Override
    public OrganizerVo getOrganizer() {
        long id = getCurrentCompetition();
        Competition competition = competitionRepository.findById(id).orElse(null);
        long organizerId = competition.getOrganizerId();
        Organizer organizer = organizerService.getById(organizerId);
        OrganizerVo organizerVo = new OrganizerVo();
        BeanUtils.copyProperties(organizer, organizerVo);
        return organizerVo;
    }

    @Override
    public void setCurrentCompetition(Long name) {
        Long id = CurrentUserUtil.getCurrentUser().getId();
        competitionEdit.put(id, name);
        log.info("设置当前修改竞赛为 {}", name);
    }

    @Override
    public Long getCurrentCompetition() {
        Long id = CurrentUserUtil.getCurrentUser().getId();
        Long name = competitionEdit.get(id);
        if (name == null) {
            throw new NullPointerException("未设置操作中的竞赛");
        }
        log.info("设置当前修改竞赛为 {}", name);
        return name;
    }

    @Override
    public List<CompetitionDetailVo> getEnrollList() {
        User user = CurrentUserUtil.getCurrentUser();
        List<EnrollCollection> enrollCollections = enrollCollectionService.findByUserId(user.getId());
        List<CompetitionDetailVo> list = new ArrayList<>();
        for (EnrollCollection item : enrollCollections) {
            CompetitionDetailVo detailVo = this.getCompetitionDetail(item.getCompetitionId());
            list.add(detailVo);
        }
        return list;
    }

    @Override
    public String answerUpload(MultipartFile file, long competitionId,
                               long paperId, long columnId, long questionId) {
        AnswerPaper answerPaperOld = answerPaperService.findByQuestionIdAndUserId(
                CurrentUserUtil.getCurrentUser().getId(), questionId);
        if (answerPaperOld != null) {
            fileService.delete(answerPaperOld.getAnswer(), "answer/" + paperId + "/");
            String targetFileName = fileService.upload(file, "answer/" + paperId + "/");
            if (!targetFileName.isEmpty()) {
                AnswerPaper answerPaper = answerPaperOld;
                answerPaper.setAnswer(targetFileName);
                int res = answerPaperService.update(answerPaper);
                if (res > 0) {
                    return targetFileName;
                }
            }
        } else {
            String targetFileName = fileService.upload(file, "answer/" + paperId + "/");
            if (!targetFileName.isEmpty()) {
                AnswerPaper answerPaper = new AnswerPaper();
                answerPaper.setId(SnowflakeUtil.nextId());
                answerPaper.setUserId(CurrentUserUtil.getCurrentUser().getId());
                answerPaper.setAnswer(targetFileName);
                answerPaper.setCompetitionId(competitionId);
                answerPaper.setPaperId(paperId);
                answerPaper.setColumnId(columnId);
                answerPaper.setQuestionsId(questionId);
                int res = answerPaperService.insert(answerPaper);
                if (res > 0) {
                    return targetFileName;
                }
            }
        }
        return null;
    }

    @Override
    public String getUploadAnswer(long questionId) {
        AnswerPaper answerPaperOld = answerPaperService.findByQuestionIdAndUserId(CurrentUserUtil.getCurrentUser().getId(), questionId);
        if (answerPaperOld != null) {
            return answerPaperOld.getAnswer();
        }
        return null;
    }

    @Override
    public List<CompetitionDetailVo> getCompetitionReviewList() {
        List<CompetitionReview> competitionReviews = competitionReviewService.findByUserId(CurrentUserUtil.getCurrentUser().getId());
        List<CompetitionDetailVo> detailVos = new ArrayList<>();
        for (CompetitionReview review : competitionReviews) {
            long competitionId = review.getCompetitionId();
            CompetitionDetailVo vo = this.getCompetitionDetail(competitionId);
            detailVos.add(vo);
        }
        return detailVos;
    }


    @Override
    public List<UserScoreVo> getEnrollUser(long competitionId) {
        List<EnrollCollection> enrollCollections = enrollCollectionService.findByCompetitionId(competitionId);
        List<UserScoreVo> userVos = new ArrayList<>();
        for (EnrollCollection collection : enrollCollections) {
            User userInfo = userService.getUserInfo(collection.getUserId());
            int score = getUserScore(userInfo.getId(),competitionId);
            UserScoreVo userVo = new UserScoreVo();
            BeanUtils.copyProperties(userInfo, userVo);
            userVo.setScore(score);
            userVos.add(userVo);
        }
        return userVos;
    }

    @Override
    public int setScore(Integer score, Long userId, Long questionId, Long competitionId) {
        CompetitionScore competitionScore = competitionScoreService.findByQuestionIdAndUserIdAndTeacherId(questionId, userId, CurrentUserUtil.getCurrentUser().getId());
        if (competitionScore != null) {
            competitionScore.setScore(score);
            return competitionScoreService.update(competitionScore);
        } else {
            CompetitionScore scoreClass = new CompetitionScore();
            scoreClass.setId(SnowflakeUtil.nextId());
            scoreClass.setScore(score);
            scoreClass.setTeacherId(CurrentUserUtil.getCurrentUser().getId());
            scoreClass.setQuestionsId(questionId);
            scoreClass.setUserId(userId);
            scoreClass.setCompetitionId(competitionId);
            return competitionScoreService.insert(scoreClass);
        }
    }

    @Override
    public CompetitionScore getScore(Long userId, Long questionId) {
        return competitionScoreService.findByQuestionIdAndUserIdAndTeacherId(questionId, userId, CurrentUserUtil.getCurrentUser().getId());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int setGradeTeacher(GradeTeacherVo vo) {
        List<CompetitionReview> review = competitionReviewService.findByCompetitionId(getCurrentCompetition());
        if (!review.isEmpty()) {
            for (CompetitionReview r : review) {
                competitionReviewService.delete(r);
            }
        }
        for (Long id : vo.getGradeTeachers()) {
            CompetitionReview competitionReview = new CompetitionReview();
            competitionReview.setId(SnowflakeUtil.nextId());
            competitionReview.setCompetitionId(getCurrentCompetition());
            competitionReview.setUserId(id);
            competitionReviewService.insert(competitionReview);
        }
        return 1;
    }

    @Override
    public List<String> getGradeTeacher() {
        List<CompetitionReview> review = competitionReviewService.findByCompetitionId(getCurrentCompetition());
        List<String> id =new ArrayList<>();
        for (CompetitionReview r: review){
            id.add(r.getUserId().toString());
        }
        return id;
    }

    public List<String> getGradeTeacher(long competitionId) {
        List<CompetitionReview> review = competitionReviewService.findByCompetitionId(competitionId);
        List<String> id =new ArrayList<>();
        for (CompetitionReview r: review){
            id.add(r.getUserId().toString());
        }
        return id;
    }

    @Override
    public List<ChartsVo> getCharts(Long competitionId) {
        Competition competition = competitionRepository.findById(competitionId).orElse(null);
        if(competition!=null){
            List<UserScoreVo> userList = this.getEnrollUser(competitionId);
            if(userList.isEmpty()){
                return null;
            }
            int TotalScore = 1;
            List<String> teachers = this.getGradeTeacher(competitionId);
            if(teachers.isEmpty()){
                return null;
            }
            ExaminationPaper paper = examinationPaperService.findById(competition.getExamPaperId());
            if (paper!=null){
                TotalScore = paper.getTotalScore();
            }
            List<ChartsVo> list = new ArrayList<>();
            for(UserScoreVo userVo : userList){
                ChartsVo chartsVo = new ChartsVo();
                float score = competitionScoreService.countScore(userVo.getId(),teachers,competitionId);
                chartsVo.setUsername(userVo.getUsername());
                chartsVo.setName(userVo.getName());
                chartsVo.setSex(userVo.getSex());
                chartsVo.setCode(userVo.getCode());
                chartsVo.setId(userVo.getId());
                chartsVo.setMail(userVo.getMail());
                chartsVo.setPhone(userVo.getPhone());
                chartsVo.setPrefilePicture(userVo.getPrefilePicture());
                chartsVo.setName(userVo.getName());
                float temp = (score/TotalScore)*100;
                chartsVo.setScore(temp);
                list.add(chartsVo);
            }
//            Collections.sort(list);
            return list;
        }
        return null;
    }

    @Override
    public int endCompetition(Long id) {
        return competitionMapper.updateStatus(id,5);
    }

    @Override
    public int reEditCompetition(long competitionId) {
        return competitionMapper.updateStatus(competitionId, UNPUBLISH);
    }

    @Override
    public Integer getUserScore(Long userId, Long competitionId) {
        return competitionScoreService.score(CurrentUserUtil.getCurrentUser().getId(),userId,competitionId);
    }

    @Override
    public List<TeacherGradeVo> getTeacherGrade(Long competitionId, Long userId, Long questionId) {
        List<CompetitionScore> competitionScores = competitionScoreService.findByUserIdAndCompetitionId(userId,competitionId,questionId);
        List<TeacherGradeVo> teacherGradeVos = new ArrayList<>();
        for (CompetitionScore score: competitionScores){
            TeacherGradeVo vo = new TeacherGradeVo();
            User user = userService.getUserInfo(score.getTeacherId());
            vo.setTeacherName(user.getName());
            vo.setTeacherUsername(user.getUsername());
            vo.setTeacherScore(score.getScore());
            vo.setCreateTime(score.getCreateDate());
            vo.setId(score.getId());
            teacherGradeVos.add(vo);
        }
        return teacherGradeVos;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCompetition(Long competitionId) {
        Competition competition = competitionRepository.findById(competitionId).orElse(null);

        int result1 = advertisePictureService.deleteByPrimaryKey(competition.getAdvertisePictureId());
        int result2 = signupInformationService.deleteByPrimaryKey(competition.getSignupInformationId());
        int result3 = competitionInformationService.deleteByPrimaryKey(competition.getInformationId());
        int result4 = organizerService.deleteByPrimaryKey(competition.getOrganizerId());
        int result5 = contactService.deleteByPrimaryKey(competition.getContactId());
        int result6 = examinationPaperService.deleteByPrimaryKey(competition.getExamPaperId());
        int result = competitionMapper.deleteByPrimaryKey(competitionId);

        return 1;
    }


}
